import dayjs from 'dayjs';

export function formatDate(date, fmt = 'yyyy-MM-dd') {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str));
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

// 发布时间格式处理
export function getFormattedPublishTime(timestamp) {
  const now = new Date();
  const date = new Date(timestamp);
  // 今日发布的内容显示：16:30
  if (now.toDateString() === date.toDateString()) {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }
  // 昨日发布的内容今天显示：昨天 14:20
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (yesterday.toDateString() === date.toDateString()) {
    return `昨天 ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
  }
  // 跨年时间显示 2022-09-10 14:20
  const currentYear = now.getFullYear();
  const targetYear = date.getFullYear();
  if (currentYear !== targetYear) {
    return dayjs(date).format('YYYY-MM-DD HH:mm');
  }
  // 其他时间显示 09-01 14:20
  return dayjs(date).format('MM-DD HH:mm');
}
